<template>
  <div class="settings-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row>
        <el-col :span="14">
          <el-form
            ref="settings-form"
            :rules="settingsRules"
            :model="user"
            label-width="80px"
          >
            <el-form-item label="编号">{{ user.id }}</el-form-item>
            <el-form-item label="手机">{{ user.mobile }}</el-form-item>
            <el-form-item label="媒体名称">
              <el-input
                prop="name"
                type="textarea"
                v-model="user.name"
              ></el-input>
            </el-form-item>
            <el-form-item prop="intro" label="媒体介绍">
              <el-input v-model="user.intro"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onUpdateUser"
                :loading="updateProfileLoading"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" :offset="2">
          <div class="avatar-action" @click="$refs.file.click()">
            <el-avatar
              class="avatar"
              shape="square"
              :size="150"
              fit="cover"
              :src="user.photo"
            ></el-avatar>
            <div>修改头像</div>
          </div>
          <input type="file" hidden ref="file" @change="onFileChange" />
        </el-col>
      </el-row>
    </el-card>
    <!-- 修改头像，弹出层 -->
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      @opened="onDialogOpened"
      @closed="onDialogClosed"
    >
      <div class="preview-image-wrap">
        <img class="preview-image" :src="previewImage" ref="preview-image" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="onUpdatePhoto"
          :loading="updatePhotoLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { getUserInfo, updateUserPhoto, updateUserInfo } from '@/api/user'
export default {
  name: 'Settings',
  components: {},
  props: {},
  data () {
    return {
      user: {
        email: '',
        id: null,
        intro: '',
        mobile: '',
        name: '',
        photo: ''
      },
      settingsRules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'change'
          }
        ],
        intro: [
          {
            required: true,
            message: '请输入简介',
            trigger: 'change'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'change'
          }
        ]
      },
      dialogVisible: false, // 修改头像弹出层的显示
      previewImage: '', // 预览蹄片
      cropper: null, // 裁切器实例
      updatePhotoLoading: false, //  更新用户头像 loading状态
      updateProfileLoading: false // 更新基本信息的loading状态
    }
  },
  computed: {},
  watch: {},
  mounted () {
    this.loadUserInfo()
  },
  beforeDestroy () {
    this.$bus.$off('update-user')
  },
  methods: {
    // 获取用户信息
    async loadUserInfo () {
      const { data } = await getUserInfo()
      // console.log(data)
      this.user = data.data
    },
    // 更新用户信息
    onUpdateUser () {
      // 验证表单
      this.$refs['settings-form'].validate(async valid => {
        if (!valid) {
          return false
        }
        // 验证过通过提交表单
        this.updateProfileLoading = true
        try {
          const { name, intro, email } = this.user
          await updateUserInfo({
            name,
            intro,
            email
          })
          this.updateProfileLoading = false
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          // 通知父组件用户信息更新
          this.$bus.$emit('update-user', this.user)
        } catch (error) {

        }
      })
    },
    // 修改头像
    onFileChange () {
      // 得到要处理的图片
      const file = this.$refs.file
      const blobData = window.URL.createObjectURL(file.files[0])
      this.previewImage = blobData
      // console.log('change')
      // 展示弹出层，预览图片
      this.dialogVisible = true
      // 解决相同图片不触发change事件 问题
      this.$refs.file.value = ''
    },
    onDialogOpened () {
      // 图片裁切器必基于 img 进行 初始化，所以image 必须是可见状态
      // 获取图片节点
      const image = this.$refs['preview-image']
      // 第一次初始化后，如果要有预览的图片发生了变化，裁切器默认不会跟新
      // 如果要预览图片发生变化更新裁切器：
      //   方式一 裁切器.replace方法
      //   方式二： 销毁裁切器，重新初始化 destroy()
      // 初始化裁切器
      // 使用方式一 裁切器.replace方法
      // if (this.cropper) {
      //   this.cropper.replace(this.previewImage)
      //   return false
      // }
      this.cropper = new Cropper(image, {
        // 裁切器初始化的比例
        aspectRatio: 1,
        viewMode: 1,
        dragMode: 'none',
        cropBoxResizable: false,
        background: false
        // // 当移动裁切器时会调用crop方法
        // crop (event) {
        //   console.log(event.detail.x)
        //   console.log(event.detail.y)
        //   console.log(event.detail.width)
        //   console.log(event.detail.height)
        //   console.log(event.detail.rotate)
        //   console.log(event.detail.scaleX)
        //   console.log(event.detail.scaleY)
        // }
      })
    },
    // 对话框关闭
    onDialogClosed () {
      // 关闭对话框，销毁裁切器
      this.cropper.destroy()
    },
    // 确定更新头像
    onUpdatePhoto () {
      this.updatePhotoLoading = true
      // 获取裁切的图像
      this.cropper.getCroppedCanvas().toBlob(async file => {
        const fd = new FormData()
        fd.append('photo', file)
        // 请求提交 fd
        await updateUserPhoto(fd)
        // console.log(data)
        // 关闭对话框
        this.dialogVisible = false
        // 更新试图展示
        this.user.photo = window.URL.createObjectURL(file)
      })
      // 请求更新用户头像
      // 关闭对话框
      // 更新试图展示
      this.updatePhotoLoading = false
      this.$message({
        type: 'success',
        message: '更新头像成功'
      })
      // 通知父组件用户信息更新
      this.$bus.$emit('update-user', this.user)
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-action {
  display: flex;
  flex-direction: column;
  align-items: center;
  .avatar {
    margin-bottom: 10px;
  }
}
.preview-image-wrap {
  .preview-image {
    display: block;
    max-width: 100%;
    height: 250px;
  }
}
</style>
